package org.cn.lennon.mybatis.executors.impl.handler;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.cn.lennon.mybatis.config.MapperStatment;
import org.cn.lennon.mybatis.factory.DefaultObjectFactory;
import org.cn.lennon.mybatis.uitl.ReflectionUtil;

public class ResultSetHandler {
	
	private MapperStatment mapperStatemnt;
	
	public ResultSetHandler(MapperStatment mapperStatemnt) {
		this.mapperStatemnt = mapperStatemnt;
	}

	public <T> T handler(PreparedStatement prepareStatement) throws SQLException {
		ResultSet rs = prepareStatement.executeQuery();
		List<Object> resultObjects = new ArrayList<Object>();
		Field[] fieldArray = mapperStatemnt.getResultType().getDeclaredFields();
		while(rs.next()) {
			Object resultObject = DefaultObjectFactory.create(mapperStatemnt.getResultType());
			for(Field field : fieldArray){  
	            ReflectionUtil.setValue(resultObject, field, getObject(rs, field));
	        }
			resultObjects.add(resultObject);
		}
		return (T) resultObjects.get(0);
	}
	
	private Object getObject(ResultSet rs, Field field) throws SQLException {
		if(field.getType() == Integer.class) {
			return rs.getInt(field.getName());
		}
		if(field.getType() == String.class) {
			return rs.getString(field.getName());
		}
		return null;
	}
}
